<template>
  <div id="app">
    <div class="container">
          {{ upload_file || "导入" }}
          <input
            type="file"
            accept=".xls,.xlsx"
            class="upload_file"
            @change="readExcel($event)"
          />
        </div>
  </div>
</template>

<script>
import xlsx from 'xlsx'

export default {
  data () {
    return {
      msg: '',
      upload_file: '',
      list: []
    }
  },
  methods: {
    readExcel (e) {
      // 获取文件对象
      const that = this
      const files = e.target.files
      if (files.length <= 0) {
        return false
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        return false
      } else {
        that.upload_file = files[0].name // 获取文件名
      }
      const fileReader = new FileReader()
      fileReader.onload = ve => {
        try {
          const data = ve.target.result
          const workbook = xlsx.read(data, {
            type: 'binary'
          })
          const wsname = workbook.SheetNames[0]
          const ws = xlsx.utils.sheet_to_json(workbook.Sheets[wsname]) // 解析到xlsx表
          that.lists = ws
          console.log(that.lists)
        } catch (e) {
          return false
        }
      }
      fileReader.readAsBinaryString(files[0])
    }
  }
}
</script>

<style lang="scss">
.container {
  border: none;
  border-radius: 4px;
  background-color: #409eff;
  height: 40px;
  margin-top: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 15px;
  min-width: 80px;
  *zoom: 1;
}

.upload_file {
  font-size: 20px;
  opacity: 0;
  position: absolute;
  filter: alpha(opacity=0);
  width: 60px;
}
</style>
